package com.zxd.interview.eightthread.stop;

/**
 * 错误的使用方式，无法正确的停止线程
 */
public class WrongWayCannotStopThread implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new WrongWayCannotStopThread());
        thread.start();
        thread.sleep(500);
        // 线程不响应停止
        thread.interrupt();
    }

    @Override
    public void run() {

            int num = 0;
            // Thread.curr..interrrupt() 之后需要 !Thread.currentThread().isInterrupted() 判断是否被中断
            while (!Thread.currentThread().isInterrupted() && num <= Integer.MAX_VALUE / 2) {
                if (num % 100 == 0) {
                    System.out.println("num =>" + num);
                    // try/catch在循环内部，当被中断之后会清除中断标记，但是此时
                    interInvoke();
                    // 比较隐蔽的内部方法try/catch
                }
                num++;
            }
            System.out.println("执行完成");

    }/**
     虽然子线程被主线程中断，但是实际上程序无法停止，由于interrupt的底层原理导致
     在使用此方式可以修复无法停止线程的问题：Thread.currentThread().interrupt();

     引申：
     1. 线程的内部方法，如果无法处理异常，通常情况下不能吞异常，而是要把问题抛给run方法去处理。
     2. 如果一定要在内部捕获异常并且处理，则建议手动在子线程内部中断并且告知调用方有可能进行线程中断。

     num =>0
     num =>100
     num =>200
     num =>300
     num =>400
     java.lang.InterruptedException: sleep interrupted
     at java.lang.Thread.sleep(Native Method)
     at com.zxd.interview.eightthread.stop.WrongWayCannotStopThread.run(WrongWayCannotStopThread.java:25)
     at java.lang.Thread.run(Thread.java:750)
     num =>500
     num =>600
     num =>700
     num =>800
     num =>900
     num =>1000
     num =>1100
     */


    private void interInvoke() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
            // 使用此方式可以修复无法停止线程的问题
//            Thread.currentThread().interrupt();

        }
    }/**
     内部方法需要谨慎处理异常，如果无法处理建议直接抛给run方法处理
     num =>0
     num =>100
     num =>200
     num =>300
     num =>400
     java.lang.InterruptedException: sleep interrupted
     at java.lang.Thread.sleep(Native Method)
     at com.zxd.interview.eightthread.stop.WrongWayCannotStopThread.interInvoke(WrongWayCannotStopThread.java:61)
     at com.zxd.interview.eightthread.stop.WrongWayCannotStopThread.run(WrongWayCannotStopThread.java:25)
     at java.lang.Thread.run(Thread.java:750)
     num =>500
     num =>600
     num =>700
    */

}
